package com.zzyl.framework.interceptor;

import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.common.constant.Constants;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Component
public class MemberInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    // 不需要认证的路径
    private List<String> excludePaths = new ArrayList<>();

    public MemberInterceptor() {
        // 添加不需要认证的路径
        excludePaths.add("/member/user/login");
        excludePaths.add("/member/user/register");
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        // 检查是否在排除列表中
        for (String excludePath : excludePaths) {
            if (requestURI.contains(excludePath)) {
                return true; // 直接放行，不需要认证
            }
        }
        // 使用通用方式获取Authorization头
        String token = request.getHeader("Authorization");
        if (StringUtils.isEmpty(token)) {
            // 兼容小写authorization头
            token = request.getHeader("authorization");
        }
        if (StringUtils.isEmpty(token)) {
            throw new BaseException("认证失败");
        }
        // 如果token以Bearer 开头，需要去掉前缀
        if (token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.substring(Constants.TOKEN_PREFIX.length());
        }
        // 校验token
        try {
            Claims claims = tokenService.parseToken(token);
            // token获取userId
            Long userId = claims.get("id", Long.class);
            UserThreadLocal.set(userId);
        } catch (Exception e) {
            throw new BaseException("认证失败");
        }
        return true; //放行
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
